var STU_lessons=[]//全局变量 存储该学生的课程
$(function () {

getWebLabs();
});
function  fillRoleAndName(){
	 var s="";
	switch (Role){
		case "admin": s=langThis( "nav_admin" );break;
		case "teacher": s=langThis( "nav_teacher" );break;
		case "student": s=langThis( "nav_student" );break;
		default:break;
	}
//	$("#roleSpan").text(s);
	$("#user").text(User);
}
function completer_click(){
	getQuerylessonname($("#querystring").val());
	$("#inputlistcontentdiv").addClass("open");
}
function caculateLessonNamesArrFormLabs(){
	if(STU_lessons.length<1){
		return [];
	}
	else{
		var  templessons=[];
		for(var i in STU_lessons){
			templessons.push(STU_lessons[i].lesson_name);
		}
		var  lessons=uniqueArray(templessons);
		return  lessons.arr;
	}
}
function caculateLessonIdsArrFormLabs(){
	if(STU_lessons.length<1){
		return [];
	}
	else{
		var  templessons=[];
		for(var i in STU_lessons){
			templessons.push(STU_lessons[i].lesson_id);
		}
		var  lessons=uniqueArray(templessons);
		return  lessons.arr;
	}
}
function getQuerylessonname(str) {
    if(STU_lessons.length<1){
        // console.log("STU_lessons is null")
        return;
    }
    var lessonNames=caculateLessonNamesArrFormLabs();
    var lessonIds=caculateLessonIdsArrFormLabs();
    var lessons;
    if(isNaN(str)){
        lessons=lessonNames;
    }
    else{
     lessons=lessonIds;
    }
	var re = str ? new RegExp(str) : /.*/;
	var lis = "";
	for (var i = 0; i < lessons.length; i++) {
		if (re.test(lessons[i])) {
			lis += '<li data-lessonid="' + lessons[i] + '">' + lessons[i] + '</li>';
		}
	}
	$("ul.dropdown-menu.querymenu").html(lis);
	var q=$("#querystring");
	if (!$("ul.dropdown-menu.querymenu>li").length) {
		$("ul.dropdown-menu.querymenu").append(langThis("kc_nomatches"));
		q.attr("data-lessonid", false);
	}
	if (q.val() === "") {
		q.attr("data-lessonid", false);
	} else {
		q.attr("data-lessonid", $("ul.dropdown-menu.querymenu>li:first-child").attr("data-lessonid"));
	}


	/*绑定查询下拉列表点击事件*/
	$("ul.dropdown-menu.querymenu>li").click(function () {
		q.val($(this).text());
		q.attr("data-lessonid", $(this).attr("data-lessonid"));

		filterLabsBylessonNameOrId($(this).text());
	});
}
function getWebLabs ( ) {
$.ajax({
		url: "lab_query_rs.action",
		type: "POST",
		data: {

                "student.id":UserID
    },
		dataType: "json",
		success: function (data){
                if(data.succeed=="true") {
                //success
               STU_lessons=data.data;
               setPagePagination(STU_lessons.length);
               firstPage();
            }
            else {
                layer.msg(langThis("lm_queryLabFail"));
            }


        },
		error: function (event) {
           layer.msg(langThis("lm_queryLabFail"));


		}
	});
}
function  fillWebLabs(start,stop){
    var  ht="";
    for(var i=start ;i<=stop;i++){
        var theLab=STU_lessons[i];
        ht+="<tr><td>"+theLab.lesson_id+"</td><td>"+theLab.lesson_name+"</td><td>";
        ht+=theLab.lab_name+"</td><td>";
        var  datas="";
        var  docs="";
        for (var j in theLab.resources){
            var theRsc=theLab.resources[j];
            if(theRsc.data_path==null){
                    docs+="<a class='btn btn-link' role='button' target=\"_blank\" href=\""+theRsc.doc_path+"\">"+theRsc.t_workspace_name+"</a>/";
            }
            else{
                datas+="<a class='btn btn-link' role='button' target=\"_blank\" href=\""+theRsc.data_path+"\">"+theRsc.t_workspace_name+"</a>/";
            }
        }
        var formartcodeurl=theLab.codeurl==null?"":theLab.codeurl;
        datas=datas.slice(0,datas.length-1);
        docs=docs.slice(0,docs.length-1);
        ht+=datas+"</td><td>"+docs+"</td>";
        if(theLab.type_id==1)
        {
        	ht+="<td><span style='height:34px;display: block;'></span></td><td></td>";
        }
        else {
                var btnLang=formartcodeurl==""?langThis("ol_submit"):langThis("pm_modify");
        		ht+="<td><a href='http://runjs.cn/code' target='_blank' role='button' class='btn btn-link'>"+langThis("ol_codeing")+"</a>/<a href='http://c.dituhui.com/apps' target='_blank' role='button' class='btn btn-link'>"+langThis("ol_mkmap")+"</a></td><td><input class='form-control urlinput' id='webAns_"+theLab.lab_id+"'value='"+formartcodeurl+"'/><a class='blueBtn' onclick='submitWebAns(this)'>"+btnLang+"</a></td>";
        }
        ht+="<td>"+webAnsStatus(theLab.codeurl,theLab.totlascore)+"</td></tr>";


    }
    $("#itemTbody_class").html(ht);
}
function submitWebAns(e) {
  var codeIput=$(e).prev();
  var code_url=codeIput.val();
  var lab_id=codeIput.attr("id").split("_")[1];
  if(code_url==""||code_url==null){
       layer.msg(langThis("ol_codeurl"));
       return;
  }else if(code_url.indexOf("http")<0){
        layer.msg(langThis("ol_httpcheck"));
       return;
  }
  $.ajax({
		url: "s_web_insert.action",
		type: "POST",
		data: { "lab_id": lab_id,
                "student_id" :UserID,
            "codeurl" : code_url   },
		dataType: "json",
		success: function (data){
                if(data.succeed=="true"){
                    layer.msg(langThis("ol_webAnsS"));
                    handleNewWebAnsStatus(codeIput.parent().next());
                }
                else{
                 layer.msg(langThis("ol_webAnsF"));
                }

        },
		error: function (event) {
            layer.msg(langThis("ol_webAnsF"));


		}
	});
}
function handleNewWebAnsStatus(dom ) {
    dom[0].innerHTML=langThis("ol_st_ye");
 }
function webAnsStatus(codeurl,score ) {
//if(codeurl==null){
//  if(score==null){
//          return langThis("ol_st_no");
//
//  }
//  else{
//  	return "error";
//  }
//}
//else{
//  if(score==null){
//       return langThis("ol_st_ye");
//  }
//  else{
//       return langThis("ol_st_ny");
//  }
//}
 if(score==null){
            return langThis("ol_st_le");

    }
    else{
    	return langThis("ol_st_fi");
    }
}

function  setPagePagination(length){
	if(length>0){
		var n = length% 10;  //每页显示10个
		var totalPage;
		if (n == 0) {
			totalPage = parseInt(length / 10);//丢弃小数部分,保留整数部分
		} else {
			totalPage = parseInt(length / 10) + 1;//丢弃小数部分,保留整数部分
		}
		$('#totalIndex').text(totalPage);
		if (totalPage >= 2) {
			fillTableDetail(0, 9);
		}
		else {
			fillTableDetail(0,length-1);
		}
	}
}
function prePage(){
	var length=STU_lessons.length;
	var p=$("#nowIndex");
	var  index=parseInt(p.text());
	if(index!=1){
		p.text(--index);
		var start = index* 10 - 10;
		var stop = index * 10 - 1;
		stop=stop>=length?length-1:stop;
		fillTableDetail(start,stop);
	}
}
function  nextPage(){
	var length=STU_lessons.length;
	var p=$("#nowIndex");
	var  index=parseInt(p.text());
	var totalPage=$("#totalIndex").text();
	if(index<totalPage){
		var s=++index;
		p.text(s);
		var start = s* 10 - 10;
		var stop = s * 10 - 1;
		stop=stop>=length?length-1:stop;
		fillTableDetail(start,stop);
	}
}
function  firstPage(){
	var length=STU_lessons.length;
	var stop=9;
	stop=	stop>=length?length-1:stop;
    $("#nowIndex").text("1");
	fillTableDetail(0,stop);
}
function  lastPage(){
	var length=STU_lessons.length;
	var p=$("#nowIndex");
	var totalPage=$("#totalIndex").text();
	p.text(totalPage);
	var start = totalPage* 10 - 10;
	var stop = totalPage * 10 - 1;
	stop=stop>=length?length-1:stop;
	fillTableDetail(start,stop);
}
function fillTableDetail(start,stop){
	if(STU_lessons.length<1){
		// console.log("stu_lessons is null");
		return;
	}
	fillWebLabs(start,stop);
}
function uniqueArray(arr) {//数组去重 并计数
    arr.sort();
    var re = {};
    re.arr = [arr[0]];
    re.count = [];
    var temp = 1;
    for (var i = 1; i < arr.length; i++) {
        if (arr[i] !== re.arr[re.arr.length - 1]) {
            re.arr.push(arr[i]);
            re.count.push(temp);
            temp = 1;
        }
        else {
            temp++;
        }
    }
    re.count.push(temp);

    return re;
}
function filterLabsBylessonNameOrId(lessonNameOrId){
	if(STU_lessons.length<1){
		// console.log("STU_lesson is null");
		return;
	}
	var  filtedLabs=[];
	for(var i  in STU_lessons){
		var thelab=STU_lessons[i];
		if(thelab.lesson_name==lessonNameOrId||thelab.lesson_id==lessonNameOrId){
			filtedLabs.push(thelab);
		}
	}
	rewriteTableDetailsBylesson(filtedLabs);
}
function rewriteTableDetailsBylesson(labs){
	    var  ht="";
    for(var i=0 ;i<labs.length;i++){
        var theLab=labs[i];
       ht+="<tr><td>"+theLab.lesson_id+"</td><td>"+theLab.lesson_name+"</td><td>";
        ht+=theLab.lab_name+"</td><td>";
        var  datas="";
        var  docs="";
        for (var j in theLab.resources){
            var theRsc=theLab.resources[j];
            if(theRsc.data_path==null){
                    docs+="<a class='btn btn-link' role='button' target=\"_blank\" href=\""+theRsc.doc_path+"\">"+theRsc.t_workspace_name+"</a>/";
            }
            else{
                datas+="<a class='btn btn-link' role='button' target=\"_blank\" href=\""+theRsc.data_path+"\">"+theRsc.t_workspace_name+"</a>/";
            }
        }
        var formartcodeurl=theLab.codeurl==null?"":theLab.codeurl;
        datas=datas.slice(0,datas.length-1);
        docs=docs.slice(0,docs.length-1);
        ht+=datas+"</td><td>"+docs+"</td>";
        if(theLab.type_id==1)
        {
        	ht+="<td><span style='height:34px;display: block;'></span></td><td></td>";
        }
        else {
            var btnLang=formartcodeurl==""?langThis("ol_submit"):langThis("pm_modify");
        	ht+="<td><a href='http://runjs.cn/code' target='_blank' role='button' class='btn btn-link'>"+langThis("ol_codeing")+"</a>/<a href='http://c.dituhui.com/apps' target='_blank' role='button' class='btn btn-link'>"+langThis("ol_mkmap")+"</a></td><td><input class='form-control urlinput' id='webAns_"+theLab.lab_id+"'value='"+formartcodeurl+"'/><a class='blueBtn' onclick='submitWebAns(this)'>"+btnLang+"</a></td>";
        }
        ht+="<td>"+webAnsStatus(theLab.codeurl,theLab.totlascore)+"</td></tr>";


    }
    $("#itemTbody_class").html(ht);
}
function  getChooseContent (){
    window.parent.setChooseContent();
  }